package com.ctgu.expresshelper.service.User.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ctgu.expresshelper.dao.UserDao;
import com.ctgu.expresshelper.entity.User;
import com.ctgu.expresshelper.service.User.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    @Autowired
    private UserDao userDao;

    @Override
    public User getUserOpenId(String username,String imgUrl,String code) {
        String authUrl="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
        authUrl = authUrl + "&appid=" + appId + "&secret=" + secret + "&js_code=" + code;
        String result = HttpUtil.get(authUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String openId = jsonObject.getStr("openid");

        User user= selectUserByOpenId(openId);
        if(user==null){
//            未注册进行注册
            User user2=new User();
            user2.setUsername(username);
            user2.setImgUrl(imgUrl);
            user2.setOpenid(openId);
            user2.setReceiveNum(0);
            user2.setSendNum(0);
            user2.setSex(0);
            userDao.addUser(user2);
            user=userDao.selectUserByOpenId(openId);
        }
        return user;
    }

    @Override
    public User selectUserByOpenId(String openId) {
        return userDao.selectUserByOpenId(openId);
    }

    @Override
    public int updateReceiveNum(int userId, int receiveNum) {

        return userDao.updateReceiveNum(userId,receiveNum);
    }

    @Override
    public int updateSendNumNum(int userId, int sendNum) {
        return userDao.updateSendNumNum(userId,sendNum);
    }
}
